<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="fn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="fn1">删除</button>
            <button @click="fn2(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      uname: '',
      age: '',
      gender: '',
      list: [
        {
          id: 1,
          uname: 'Tom',
          age: '19',
          gender: '男',
        },
        {
          id: 2,
          uname: 'Jone',
          age: '21',
          gender: '女',
        },
        {
          id: 3,
          uname: '小李',
          age: '18',
          gender: '男',
        },
      ],
      setId: null,
    }
  },
  methods: {
    fn() {
      if (this.uname === '' || this.age === '' || this.gender === '') {
        alert('请输入数据')
        return
      }
      if (this.setId === null) {
        this.list.push({
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        })
      } else {
        const obj = this.list[this.setId]
        obj.uname = this.uname
        obj.age = this.age
        obj.gender = this.gender
        this.setId = null
        this.uname = ''
        this.age = ''
        this.gender = ''
      }
    },
    fn1(index) {
      this.list.splice(index, 1)
    },
    fn2(index) {
      const arr = this.list[index]
      this.uname = arr.uname
      this.age = arr.age
      this.gender = arr.gender
      this.setId = index
    },
  },
}
</script>
